/*
 * Copyright © 2015 The Gravitee team (http://gravitee.io)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.gravitee.apim.infra.query_service.audit;

import io.gravitee.apim.core.audit.query_service.AuditEventQueryService;
import io.gravitee.repository.management.model.Audit;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
import org.reflections.Reflections;
import org.springframework.stereotype.Service;

@Service
public class AuditEventQueryServiceImpl implements AuditEventQueryService {

    private static final List<String> events = new ArrayList<>();

    @Override
    public List<String> listAllApiAuditEvents() {
        if (events.isEmpty()) {
            Set<Class<? extends Audit.ApiAuditEvent>> subTypesOf = new Reflections("io.gravitee.repository.management.model")
                .getSubTypesOf(Audit.ApiAuditEvent.class);
            for (Class<? extends Audit.ApiAuditEvent> clazz : subTypesOf) {
                if (clazz.isEnum()) {
                    events.addAll(
                        Stream.of(clazz.getEnumConstants()).map(Audit.AuditEvent.class::cast).map(Audit.AuditEvent::name).toList()
                    );
                }
            }
            events.sort(Comparator.naturalOrder());
        }

        return events;
    }
}
